<?php

/**
 * 身份验证
 * @global type $class
 * @global type $method
 * @global type $CI
 */
function authenticate() {
    global $class, $method, $CI;
    
    if ($class == 'welcome' || $class == 'test') {
        /* 控制器是welcome，无需验证 */
        return;
    }

    /* 验证登录 */
    $message = '您已经超过 ' . ($CI->config->item('sess_expiration') / 60)  . 
            ' 分钟未使用系统，请重新登录。';

    $u_id = $CI->session->userdata('uid');
    if (empty($u_id)) {
        if ($CI->input->is_ajax_request()) {
            set_status_header(401);
            exit('<div>' . $message . ''.
                    '<input type="hidden" value="' . site_url('welcome/login') . '" /></div>');
        } else {
            $CI->session->set_flashdata('relogin', $message);
            redirect('welcome/login', 'refresh');
        }
    }
    
    /* 验证权限 */
    if ($class == 'user' && $method == 'view') {
        /* 查看个人资料，修改密码无需验证权限 */
        return;
    }

    $CI->load->model('User_role_model');
    $role_ids = $CI->User_role_model->get_user_rids($u_id);

    if (in_array(ROLE_ADMINISTRATOR, $role_ids)) {
        /* 拥有管理员权限，通过验证 */
        return;
    }
    
    $CI->load->config('role_privileges');
    $role_privileges = $CI->config->item('role_privileges');
    $privilege_actions = $CI->config->item('privilege_actions');
    
    $passed = false; // 初始值，未通过验证
    foreach ($role_ids as $rid) {
        foreach ($role_privileges[$rid] as $priv) {
            foreach ($privilege_actions[$priv] as $controller => $actions) {
                if ($class == $controller && in_array($method, $actions)) {
                    $passed = true;
                    break;
                }
            }
        }
    }

    if (!$passed) {
        redirect('/welcome/error/' . urlencode('对不起，您没有权限执行此操作！'), 'refresh');
    }
}
